using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Circles : MonoBehaviour
{
	
	//private LineRenderer lineRenderer;
	
	public List<GameObject> circlesGameObjects;
	private GameObject currentCircle;
	private float width = 0.1f;
	private int nbCirclePoint = 100;
	
	void Awake ()
	{
		circlesGameObjects = new List<GameObject> ();
	}
	
	// Use this for initialization
	void Start ()
	{
		
	}
	
	// Update is called once per frame
	void Update ()
	{

		if (Input.GetMouseButtonDown (0)) {
			currentCircle = createNewCircle (width); // Add Circle GO + get Ref to it
			currentCircle.transform.position = getMouseImpactPoint ();
		}
	
		if (Input.GetMouseButton (0)) {
			LineRenderer circleLineRenderer = currentCircle.GetComponent<LineRenderer> ();
			float radius = Vector3.Distance (currentCircle.transform.position, getMouseImpactPoint ());
			makeCircle (ref circleLineRenderer, nbCirclePoint, radius);
		}
	}
	
	public GameObject createNewCircle (float width)
	{
		GameObject c = new GameObject ("Circle");
		LineRenderer lineRenderer = c.AddComponent<LineRenderer> ();
		lineRenderer.SetWidth (width, width);
		lineRenderer.useWorldSpace = false;
		circlesGameObjects.Add (c);
		return c;
	}
	
	public static void makeCircle (ref LineRenderer lineR, int circleResolution, float pRadius)
	{
		lineR.SetVertexCount (circleResolution);
		
		Vector3 point = Vector3.zero;
		float teta = 0;
		float deltaAngle = 360.0f / circleResolution;
		
		for (int i = 0; i < circleResolution; i++) {
			point.x = Mathf.Cos (Mathf.Deg2Rad * teta) * pRadius;
			point.z = Mathf.Sin (Mathf.Deg2Rad * teta) * pRadius;
			teta = teta + deltaAngle;
			lineR.SetPosition (i, point);
		}
	}
	
	public static Vector3 getMouseImpactPoint ()
	{		
		Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
		RaycastHit hit;

		if (Physics.Raycast (ray, out hit, Mathf.Infinity)) {
			return hit.point;
		}
	
		return Vector3.zero;
	}

}
